package org.gongliang.jsmile.config.oss.cloud;


import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.gongliang.jsmile.common.enums.KException;
import org.gongliang.jsmile.common.exception.JSmileException;
import org.gongliang.jsmile.config.oss.OSSConfig;
import org.gongliang.jsmile.config.oss.OSSService;

import com.google.common.collect.Lists;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;

/**
 * 七牛云存储
 * 
 * @author 亮仔
 *
 */
public class QiniuService extends OSSService {

	private UploadManager uploadManager;
	private String token;
	private BucketManager bucketManager;

	public QiniuService() {
		this.config = OSSConfig.me();

		// 初始化
		init();
	}

	private void init() {
		Configuration cfg = new Configuration(Zone.autoZone());
		Auth auth = Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey());
		uploadManager = new UploadManager(cfg);
		bucketManager = new BucketManager(auth, cfg);
		token = auth.uploadToken(config.getQiniuBucketName());
	}

	@Override
	public String upload(byte[] data, String path) {
		try {
			Response res = uploadManager.put(data, path, token);
			if (!res.isOK()) {
				throw new JSmileException("上传七牛出错：" + res.toString());
			}
		} catch (Exception e) {
			throw new JSmileException("上传文件失败，请核对七牛配置信息!", e);
		}

		return config.getQiniuDomain() + "/" + path;
	}

	@Override
	public String upload(InputStream inputStream, String path) {
		try {
			byte[] data = IOUtils.toByteArray(inputStream);
			return this.upload(data, path);
		} catch (IOException e) {
			throw new JSmileException(KException.FILE_UPLOAD_ERROR, e);
		}
	}

	@Override
	public String down(String path, String localPath) {
		return null;
	}

	@Override
	public void delete(String path) {
		try {
			bucketManager.delete(config.getQcloudBucketName(), path);
		} catch (QiniuException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<String> listFiles(String path) {
		List<String> urls = Lists.newArrayList();
		BucketManager.FileListIterator fileListIterator = bucketManager
				.createFileListIterator(config.getQcloudBucketName(), path);
		while (fileListIterator.hasNext()) {
			// 处理获取的file list结果
			FileInfo[] items = fileListIterator.next();
			for (FileInfo item : items) {
				System.out.println(item.key);
				System.out.println(item.hash);
				System.out.println(item.fsize);
				System.out.println(item.mimeType);
				System.out.println(item.putTime);
				System.out.println(item.endUser);
			}
		}
		return urls;
	}
}
